package com.atguigu.dw.gmallpublisher.service.impl

import com.atguigu.constan.ConstanVal
import com.atguigu.dw.gmallpublisher.esdsl.SaleDetailDsl
import com.atguigu.dw.gmallpublisher.service.SaleDetailService
import com.atguigu.dw.gmallpublisher.util.EsUtil
import org.json4s.jackson.Serialization
import org.springframework.stereotype.Service

/**
 * description ：销售查询接口实现
 * author      ：剧情再美终是戏 
 * mail        : 13286520398@163.com
 * date        ：Created in 2020/2/20 20:23
 * modified By ：
 * version:    : 1.0
 */
@Service
class SaleDetailServiceImpl extends SaleDetailService {
  /**
   * 查询 es 中的销售表相关信息，包含根据字段聚合的功能
   *
   * @Author 剧情再美终是戏
   * @Date 2020/2/20 20:24
   * @param date
   * @param keyword
   * @param startPage
   * @param size
   * @param aggField
   * @param aggSize
   * @return scala.collection.immutable.Map<java.lang.String,java.lang.Object>
   * @Version 1.0
   **/
  override def getSaleDetailAndAggResultByAggField(date: String,
                                                   keyword: String,
                                                   startPage: Int,
                                                   size: Int,
                                                   aggField: String,
                                                   aggSize: Int) = {
    // 构建 es 查询 dsl
    val dsl = SaleDetailDsl.getSaleDetailAndAggResultByAggFieldDsl(date, keyword, startPage, size, aggField, aggSize)

    // 查询 es 获取结果
    val result = EsUtil.query(ConstanVal.ES_INDEX_GMALL0830_SALE_DETAIL, dsl)

    val resultJson = result.getJsonObject

    // 获取 hits 层
    val his = resultJson.getAsJsonObject("hits")
    println("his-------------" + his)
    val hitss = his.get("hits").getAsJsonArray
    println("hitss-------------" + hitss)

    // 获取 agg 层
    val agg = resultJson.getAsJsonObject("aggregations")
    println("agg-------------" + agg)

    // 解析查询结果
    //Map("total" -> total, "aggMap" -> aggMap, "detail" -> detailList)
    val resultMap = Map(
      "total" -> his.get("total").getAsString,
      "aggMap" -> agg.getAsJsonObject("groupby_user_age").get("buckets").getAsJsonArray,
      "detail" -> hitss)
    import org.json4s.DefaultFormats
    val resultStr = Serialization.write(resultMap)(DefaultFormats)
    resultStr
  }
}
